package com.coding.service;

import com.coding.mapper.LikeMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Set;

/**
 * @author Cynicism
 * @version 1.0
 * @project DyApp
 * @description
 * @date 2024/7/11 11:04:30
 */
@Service
@Slf4j
public class LikeService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Resource
    private SqlSessionFactory sqlSessionFactory;

    private static final String REDIS_LIKE_KEY_PREFIX = "like_count:";

    @Scheduled(fixedRate = 10000) // 每10秒执行一次
    public void syncLikesToDatabase() {
        Set<String> keys = redisTemplate.keys(REDIS_LIKE_KEY_PREFIX + "*");

        if (keys == null || keys.isEmpty()) {
            return;
        }

        SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH, false);
        LikeMapper mapper = sqlSession.getMapper(LikeMapper.class);

        for (String key : keys) {
            String liveStreamId = key.substring(REDIS_LIKE_KEY_PREFIX.length());
            String likeCount = redisTemplate.opsForValue().get(key);

            mapper.addLike(Long.parseLong(liveStreamId), Integer.parseInt(likeCount));
            log.info("同步直播 {} 的点赞数到数据库：{}", liveStreamId, likeCount);

            // 清空Redis中的点赞数
//            redisTemplate.delete(key);
        }

        sqlSession.commit();
        sqlSession.close();
    }
}
